package org.dropme.server.server;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dropme.server.PMF;
import org.dropme.server.model.Litter;

import com.google.appengine.repackaged.org.json.JSONArray;
import com.google.appengine.repackaged.org.json.JSONException;
import com.google.appengine.repackaged.org.json.JSONObject;

public class PickLitterServlet extends HttpServlet {

	private static final long serialVersionUID = 2325583887470472065L;

	@SuppressWarnings("unchecked")
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String lat, lon;

		PersistenceManager manager = PMF.get().getPersistenceManager();

		Query query = manager.newQuery(Litter.class);
		List<Litter> litters;

		if ((lat = req.getParameter("latitude")) != null
				&& (lon = req.getParameter("longitude")) != null) {
			Double latitude = Double.parseDouble(lat);
			Double longitude = Double.parseDouble(lon);

			query.declareParameters("Long tag");
			query.setFilter("this.geoTag == tag");
			litters = (List<Litter>) query.execute(Litter.createGeoTag(latitude, longitude));
		} else {
			litters = (List<Litter>) query.execute();
		}

		JSONArray jsonArray = new JSONArray();

		for (Litter litter : litters) {
			jsonArray.put(litter.toJSON());
		}

		JSONObject results = new JSONObject();
		try {
			results.put("results", jsonArray);
			resp.getWriter().append(results.toString());
		} catch (JSONException e) {
			resp.getWriter().append(jsonArray.toString());
		}

	}

}
